import {
    app,
    BrowserWindow,
    ipcMain
} from 'electron';
import * as eRemoteMain from '@electron/remote/main';
import * as log from 'electron-log';
import { MainWindow } from './src/windows/mainWindow';
import { DBDataContext } from './src/core/services/domain/dataContext';

eRemoteMain.initialize();
app.commandLine.appendSwitch("ignore-certificate-errors");
if (process.env.NODE_ENV == 'dev') {
    process.env.USER_DIR = "./";
}
else {
    process.env.USER_DIR = app.getPath('userData') + "/";
    log.info(process.env.USER_DIR, app.getPath('exe'));
    console.error = log.error;
    console.log = log.log;
}

let mainWindow: BrowserWindow;
function createWindow() {
    const mainWin = new MainWindow({
        closeHandle: () => {
        },
        readyToShowHandle: () => {
        }
    })
    eRemoteMain.enable(mainWin.win.webContents);

    ipcMain.on('app.exit', () => {
        app.exit();
    })
}

app.on('ready', async () => {
    await DBDataContext.Current.Connect();
    await DBDataContext.Current.SyncDB();

    require("./src/api/app");

    createWindow();
})

// Quit when all windows are closed.
app.on('window-all-closed', () => {
    // On macOS it is common for applications and their menu bar to stay active
    // until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        app.quit();
    }
})

app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the dock icon is
    // clicked and there are no other windows open.
    //
    if (mainWindow === null) {
        createWindow();
    }
})

process.on('uncaughtException', function (error) {
    // closeAllWin();
    console.error('uncaughtException', error);
})

const singleInstance = app.requestSingleInstanceLock();
if (!singleInstance) {
    app.quit();
} else {
    app.on('second-instance', () => {
        if (mainWindow) {
            if (mainWindow.isMinimized())
                mainWindow.restore();
            mainWindow.focus();
        }
    })
}
